import os
import time

from werkzeug.utils import secure_filename

from settings import Setting
from util.FileUtil import create_folder
from util.OssUtil import upload_file_to_oss
from util.WebUtil import get_login_username


def save_file_to_local(file):
    save_path = ''
    relative_file = ''
    if file:
        username = get_login_username()
        create_date = time.strftime("%Y-%m-%d", time.localtime())
        file_name = secure_filename(file.filename)
        file_name_split = file_name.split('.')
        if len(file_name_split) >= 2:
            file_name = "{}.{}".format(hash(file_name_split[0]), file_name_split[1])
        else:
            file_name = hash(file_name)
        upload_folder = Setting.upload_path
        relative_path = "{}/user/{}/article/{}".format(upload_folder, username, create_date)
        relative_file = "{}/{}".format(relative_path, file_name)
        # folder
        real_path = '{}/{}'.format(Setting.app_path, relative_path)
        create_folder(real_path)
        save_path = os.path.join(Setting.app_path, relative_file)
        file.save(save_path)
    return save_path, relative_file


def save_file_to_oss(file, new_file):
    return upload_file_to_oss(file, new_file)
